// pages/index/suggest/suggest.js
import Dialog from "../../../miniprogram_npm/@vant/weapp/dialog/dialog"
import Toast from "../../../miniprogram_npm/@vant/weapp/toast/toast"

const app = getApp()
const log = new app.appLogs()
const http = new app.appHttp()
Page({

    /**
     * 页面的初始数据
     */
    data: {
        theme: {},
        //建议
        suggestDesc: '',
        phone: '',
        suggestType: null,
        suggestTypeList: [],
        suggestTypeShow: false,
        //附件列表
        fileList: [],
        //反馈记录
        //列表控制
        isRecordRefresh: false,
        //反馈记录列表
        recordList: [],
        pageNumber: 1,
        pageSize: 10,
        isNotData: false,
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        if (options.flag != null && options.flag != undefined && options.flag.length > 0
            && options.name != null && options.name != undefined && options.name.length) {
            this.setData({
                suggestType: {
                    flag: options.flag,
                    name: options.name
                }
            })
        }
        this.setData({
            theme: app.globalData.theme
        })
        this.getPhoneNum()
    },


    /**
     * 实时监听建议输入框
     * @param e
     */
    onInputSuggestDesc: function (e) {
        this.setData({
            suggestDesc: e.detail.value
        })
    },

    /**
     * 实时监听联系电话输入框
     * @param e
     */
    onPhoneInput: function (e) {
        this.setData({
            phone: e.detail.value
        })
    },

    /**
     * 添加附件
     * @param e
     */
    onCameraFile: function (e) {
        wx.chooseImage({
            count: 9,
            sizeType: ['compressed'],
            sourceType: ['album', 'camera'],
            success: res => {
                if (this.data.fileList.length < 9) {
                    res.tempFiles.forEach(item => {
                        if (this.data.fileList.length < 9) {
                            //上传图片到服务器
                            http.upFile(item.path, "feedback").then(res => {
                                if (res.code === http.REQUEST_OK) {
                                    let data = {
                                        attachment_name: res.data.name,
                                        attachment_url: res.data.url,
                                        attachment_type: 1
                                    }
                                    this.data.fileList.push(data)
                                    this.setData({
                                        fileList: this.data.fileList
                                    })
                                }
                            })
                        }
                    })
                }
            }
        })
    },

    /**
     * 预览图片
     * @param e
     */
    onFilePreview: function (e) {
        const index = e.currentTarget.dataset.index
        wx.previewImage({
            urls: [this.data.fileList[index].attachment_url]
        })
    },

    /**
     * 删除附件
     * @param e
     */
    onFileDelete: function (e) {
        const index = e.currentTarget.dataset.index
        this.data.fileList.splice(index, 1)
        this.setData({
            fileList: this.data.fileList
        })
    },

    /**
     * 删除图片
     */
    deleteImage: function (e) {
        const than = this
        const index = e.detail.index
        this.data.fileList.splice(index, 1)
        than.setData({
            fileList: than.data.fileList
        })

    },
    /**
     * 图片上传
     */
    afterRead: function (e) {
        const than = this
        for (let i = 0; i < e.detail.file.length; i++) {
            than.data.fileList.push({
                url: e.detail.file[i].path,
                name: e.detail.file[i].size
            })
        }
        than.setData({
            fileList: than.data.fileList
        })
    },

    /**
     * 提交建议信息
     * @param e
     */
    onSubmitSuggest: function (e) {
        const _this = this
        //判断建议内容
        if (_this.data.suggestDesc.length <= 0) {
            Dialog.alert({
                title: "温馨提示",
                message: "反馈内容不能为空"
            }).then(() => {
            })
            return false
        }
        if (_this.data.suggestType == null) {
            Dialog.alert({
                title: "温馨提示",
                message: "反馈类型不能为空"
            }).then(() => {  })
            return false
        }
        if (_this.data.phone.length <= 0) {
            Dialog.alert({
                title: "温馨提示",
                message: "联系电话不能为空"
            }).then(() => {
            })
            return false
        }
        if (_this.data.phone.length < 11) {
            Dialog.alert({
                title: "温馨提示",
                message: "请输入正确的联系电话"
            }).then(() => {
            })
            return false
        }
        Toast.loading({
            duration: 0,
            message: "正在提交..."
        })
        let files = []
        let upFileNumber = 0

        _this.data.fileList.forEach((item, index) => {
            //上传图片到服务器
            http.upFile(item.url, "feedback").then(res => {
                if (res.code === http.REQUEST_OK) {
                    let data = {
                        attachment_name: res.data.name,
                        attachment_url: res.data.url,
                        attachment_type: 1
                    }
                    files.push(data)
                }
                upFileNumber++
            },err => {
                upFileNumber++
            })
        })
        let temp = setInterval(() => {
            if (upFileNumber >= _this.data.fileList.length){
                clearInterval(temp)
                log.e("开始提交")
                http.postJson(app.globalData.xw_api_url + "feedback/insert", {
                    unit_code: app.globalData.unitCode,
                    description: _this.data.suggestDesc,
                    phone: _this.data.phone,
                    feedback_type: _this.data.suggestType.flag,
                    feedback_type_name: _this.data.suggestType.dic_value,
                    attachment_list: files
                }).then(res => {
                    if (res.data.code === http.REQUEST_OK) {
                        setTimeout(() => {
                            Toast.success("提交成功")
                            wx.navigateBack()
                        }, 500)
                    } else {
                        Toast.fail(res.data.msg)
                    }
                }, err => {
                    Toast.fail("网络异常，请稍后再试")
                })
            }
        },1000)
    },


    /**
     * 反馈记录下拉刷新
     * @param e
     */
    onRecordRefresh: function (e) {
        this.setData({
            pageNumber: 1,
            isRecordRefresh: true,
        })
        this.data.recordList = []
        this.getRecordList()
    },

    /**
     * 反馈记录上拉加载更多
     * @param e
     */
    onRecordLower: function (e) {
        this.data.pageNumber += 1
        this.getRecordList()
    },

    /**
     * 获取反馈记录列表
     */
    getRecordList: function () {
        http.get(app.globalData.xw_api_url + "feedback/page", {
            page_size: this.data.pageSize,
            page_number: this.data.pageNumber,
            // unit_code: "86.001"
            unit_code: app.globalData.unitCode,
            creator_id: app.globalData.userInfo.applet_user_id
        }).then(res => {
            if (res.data.code === http.REQUEST_OK) {
                let list = this.data.recordList
                if (res.data.data.list.length <= 0) {
                    this.setData({
                        isNotData: true
                    })
                }
                res.data.data.list.forEach(item => {
                    if (item.attachment_url_concat != null) {
                        item.attachment_url_concat = item.attachment_url_concat.split(",")
                    }
                    list.push(item)
                })
                setTimeout(() => {
                    this.setData({
                        recordList: list,
                        isRecordRefresh: false
                    })
                }, 500)
            } else {
                Toast.fail(res.msg)
                this.setData({
                    isRecordRefresh: false
                })
            }
        }, err => {
            Toast.fail("网络异常，请稍后再试")
            this.setData({
                isRecordRefresh: false
            })
        })
    },

    /**
     * 跳转反馈记录详情
     * @param e
     */
    onRecordInfo: function (e) {
        const id = e.currentTarget.dataset.id
        log.e("反馈记录id: " + id)
        wx.navigateTo({
            url: "./detail/detail?id=" + id
        })
    },


    /**
     * 切换标签
     * @param e
     */
    onTabChange: function (e) {
        if (e.detail.index == 1) {
            if (this.data.recordList.length <= 0) {
                this.setData({
                    pageNumber: 1,
                    recordList: []
                })
                this.getRecordList()
            }
        }
    },


    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {

    },
    /**
     * 获取电话号码
     */
    getPhoneNum: function () {
        const than = this
        http.get("people_info/people", {
            people_id: app.globalData.userInfo.people_id,//'8a8080d373991a3b0173991a3bce0000'
        }).then((res) => {
            if (res.data.code != 200) {
                wx.getStorage({
                    key: "phone",
                    success: function (res) {
                        if (res.data.length == 11) {
                            than.setData({
                                phone: res.data
                            })
                        } else {
                            Dialog.confirm({
                                title: '提示',
                                message: '为了方便您的操作，请先绑定手机号',
                                confirmButtonOpenType: "getPhoneNumber"
                            }).then(() => {
                                setTimeout(() => {
                                    Dialog.close();
                                }, 1000);
                            }).catch(() => {
                                Dialog.close();
                            });
                        }
                    }
                })
            } else {
                if (res.data.data.phone.length <= 0) {
                    wx.getStorage({
                        key: "phone",
                        complete: function (res) {
                            log.e(JSON.stringify(res))
                            if (res.errMsg != 'getStorage:fail data not found') {
                                than.setData({
                                    phone: res.data
                                })
                            } else {
                                Dialog.confirm({
                                    title: '提示',
                                    message: '为了方便您的操作，请先绑定手机号',
                                    confirmButtonOpenType: "getPhoneNumber"
                                }).then(() => {
                                    setTimeout(() => {
                                        Dialog.close();
                                    }, 1000);
                                }).catch(() => {
                                    Dialog.close();
                                });
                            }
                        }
                    })
                } else {
                    than.setData({
                        phone: res.data.data.phone
                    })
                }
            }
        })
    },

    getPhoneNumber: function (e) {
        const than = this
        wx.login({
            success: function (r) {
                http.get("applet/user/wxDecryptPhone", {
                        appid: app.globalData.appId,
                        code: r.code,
                        iv: e.detail.iv,
                        encryptedData: e.detail.encryptedData,
                    }
                ).then((res) => {
                    if (res.data.code == 200) {
                        wx.setStorage({
                            key: "phone",  // 存储的key值
                            data: res.data.data.phoneNumber   // 需要存储的值
                        })
                        than.setData({
                            phone: res.data.data.phoneNumber
                        })
                    }
                })
            }
        })
    },

    /**
     * 关闭弹窗
     */
    onClose: function () {
        this.setData({
            suggestTypeShow: false
        })
    },

    /**
     * 反馈类型
     * @param e
     */
    onSuggestType: function (e) {
        if (this.data.suggestTypeList.length <= 0) {
            this.getSuggestType()
        } else {
            this.setData({
                suggestTypeShow: true
            })
        }
    },
    onSuggestTypeSelect: function (e) {
        this.setData({
            suggestType: e.detail,
            suggestTypeShow: false
        })
    },

    /**
     * 获取反馈类型
     */
    getSuggestType: function () {
        Toast.loading({
            duration: 0,
            message: "加载中..."
        })
        http.get(app.globalData.xw_system_url + "dic/getDicListByName/open",{
            name: "D0125"
        }).then(res => {
            if (res.data.code === http.REQUEST_OK) {
                Toast.clear()
                res.data.data.forEach(item => {
                    item.name = item.dic_value
                })
                this.setData({
                    suggestTypeList: res.data.data,
                    suggestTypeShow: true
                })
            } else {
                Toast.fail(res.data.msg)
            }
        }, err => {
            Toast.fail("获取数据失败")
        })
    },
})